<template>
  <div class="app-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <el-row>
            <el-col :span="20">{{ form.title }}</el-col>
            <el-col :span="4" style="color: grey;">最新连载时间:{{ parseTime(form.modified, '{y}-{m}-{d}') }}</el-col>
          </el-row>
        </div>
      </template>
      <!-- 对文章缩略图进行展示 -->
      <el-carousel :interval="4000" type="card" height="400px" style="width: 100%;">
        <el-carousel-item v-for="(image, index) in form.thumbnail" :key="index" :width="300" :height="300">
          <image-preview :src="image" :width="400" :height="400" style="position: absolute; left: 20%;" />
        </el-carousel-item>
      </el-carousel>
      <div class="article-content">
        <div v-html="form.content" class="content"></div>
      </div>
      <div class="article-info">
        <el-descriptions title="文章信息" :column="2" border>
          <el-descriptions-item label="发表时间">{{ parseTime(form.created, '{y}-{m}-{d}') }}</el-descriptions-item>
          <el-descriptions-item label="修改时间">{{ parseTime(form.modified, '{y}-{m}-{d}') }}</el-descriptions-item>
          <el-descriptions-item label="文章分类">
            <dict-tag :options="category" :value="form.categories" />
          </el-descriptions-item>
          <el-descriptions-item label="文章标签">{{ form.tags }}</el-descriptions-item>
          <el-descriptions-item label="是否允许评论">
            <dict-tag :options="comment_switch" :value="form.allowComment" />
          </el-descriptions-item>
          <el-descriptions-item label="点击量">{{ form.statistic?.hits }}</el-descriptions-item>
          <el-descriptions-item label="评论总数">{{ form.statistic?.commentsNum }}</el-descriptions-item>
        </el-descriptions>
      </div>
      <div class="article-author">
        <el-descriptions title="作者信息" :column="2" border>
          <el-descriptions-item label="昵称">{{ user.nickName }}</el-descriptions-item>
          <el-descriptions-item label="头像">
            <image-preview :src="user.avatar" fit="cover" style="width: 100px; height: 100px; border-radius: 50%;" />
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <div class="comments-section">
        <label style="font-size: 24px; font-weight: bold;">评论</label>
        <el-button type="primary" icon="el-icon-edit" style="margin-left: 10px; margin-bottom: 5px;"
          @click="releaseComment()" v-if="form.allowComment != 0">发布评论</el-button>
        <el-table :data="visibleComments" style="width: 100%; margin-top: 20px;">
          <el-table-column label="评论内容" align="left" width="700px">
            <template #default="scope">
              <span>{{ scope.row.content }}</span>
            </template>
          </el-table-column>
          <el-table-column label="评论作者" align="center" prop="author" />
          <el-table-column label="头像" align="center">
            <template #default="scope">
              <image-preview :src="scope.row.avatar" fit="cover"
                style="width: 50px; height: 50px; border-radius: 50%;" />
            </template>
          </el-table-column>
          <el-table-column label="评论时间" align="center" prop="created">
            <template #default="scope">
              <span>{{ parseTime(scope.row.created, '{y}-{m}-{d}') }}</span>
            </template>
          </el-table-column>
        </el-table>
        <div v-if="loadingComments" class="loading-comments">加载中...</div>
        <div v-if="noMoreComments" class="no-more-comments">没有更多评论了</div>
      </div>
    </el-card>

    <!-- 新增/修改评论对话框 -->
    <el-dialog :title="commentTitle" v-model="commentDialog" width="600px" append-to-body>
      <el-form ref="commentRef" :model="commentForm" :rules="commentRules" label-width="120px">
        <el-form-item label="评论内容" prop="content">
          <el-input v-model="commentForm.content" type="textarea" :rows="4" placeholder="请输入评论内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitCommentForm">确 定</el-button>
          <el-button @click="cancelComment">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { useRoute } from 'vue-router';
import { getCurrentInstance } from 'vue';
import { getArticle } from "@/api/show/article";
import { getUser } from "@/api/system/user";
import { parseTime } from "@/utils/ruoyi";
import { ElCarousel, ElCarouselItem } from 'element-plus';
import { getComment, addComment, updateComment } from "@/api/show/comment";

const { proxy } = getCurrentInstance();
const { comment_switch, category } = proxy.useDict('comment_switch', 'category');
const route = useRoute();
const articleId = route.params.id;

const form = ref({
  statistic: {
    hits: 0,
    commentsNum: 0
  },
  thumbnail: [] // 添加 thumbnail 数组
});
const loadingComments = ref(false);
const noMoreComments = ref(false);
const comments = ref([]);
const visibleComments = ref([]);
const pageSize = 10;
const currentPage = ref(1);
const user = ref({});
const avatar = ref('');

const commentDialog = ref(false);
const commentTitle = ref('');
const commentForm = ref({
  id: null,
  content: '',
  articleId: articleId,
  author: '',
  created: ''
});
const commentRules = ref({
  content: [
    { required: true, message: "评论内容不能为空", trigger: "blur" }
  ]
});

function fetchComments() {
  if (loadingComments.value || noMoreComments.value) return;
  loadingComments.value = true;
  getArticle(articleId).then(response => {
    form.value = response.data;
    console.log('Response Data:', response.data); // 添加日志
    // 根据用户ID获取用户信息
    getUser(response.data.userId).then(response => {
      user.value = response.data;
    }).catch(error => {
      console.error('Error fetching user:', error);
    });
    if (response.data && response.data.statistic) {
      form.value.statistic = response.data.statistic;
    } else {
      console.error('Statistic data not found in response:', response.data);
    }
    if (response.data && response.data.comments) {
      comments.value = response.data.comments;
      visibleComments.value = comments.value.slice(0, currentPage.value * pageSize);
      if (visibleComments.value.length >= comments.value.length) {
        noMoreComments.value = true;
      }
    } else {
      console.error('Comments data not found in response:', response.data);
    }
    if (response.data && response.data.thumbnail) {
      // 将字符串通过逗号分割并赋值给 form.thumbnail
      form.value.thumbnail = response.data.thumbnail.split(',').map(url => url.trim());
    } else {
      console.error('thumbnail data not found in response:', response.data);
    }
    loadingComments.value = false;
  }).catch(error => {
    console.error('Error fetching article:', error);
    loadingComments.value = false;
  });
}

onMounted(() => {
  fetchComments();
});

watch(currentPage, () => {
  fetchComments();
});

function handleScroll(event) {
  const { scrollTop, clientHeight, scrollHeight } = event.target;
  if (scrollTop + clientHeight >= scrollHeight - 10) {
    currentPage.value++;
  }
}

// 进行发布评论(打开发布评论对话框)
function releaseComment() {
  commentTitle.value = "发布评论";
  commentForm.value = {
    id: null,
    content: '',
    articleId: articleId,
    author: user.value.nickName,
    created: new Date().toISOString()
  };
  commentDialog.value = true;
}

// 将评论发到后端
function submitCommentForm() {
  proxy.$refs["commentRef"].validate(valid => {
    addComment(commentForm.value).then(response => {
      proxy.$modal.msgSuccess("新增成功");
      commentDialog.value = false;
      location.reload();

    });
  }
  );
}

// 取消评论
function cancelComment() {
  commentDialog.value = false;
  resetCommentForm();
}

// 重置评论表单
function resetCommentForm() {
  commentForm.value = {
    id: null,
    content: '',
    articleId: articleId,
    author: user.value.nickName,
    created: new Date().toISOString()
  };
  proxy.resetForm("commentRef");
}
</script>
<style scoped>
.box-card {
  width: 100%;
  margin-top: 20px;
}

.article-content {
  margin-bottom: 20px;
}

.content {
  white-space: pre-wrap;
}

.comments-section {
  margin-top: 20px;
}

.loading-comments,
.no-more-comments {
  text-align: center;
  margin-top: 10px;
}

.el-carousel__item h3 {
  color: #475669;
  opacity: 0.75;
  line-height: 300px;
  margin: 0;
  text-align: center;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}

/* 自定义对话框样式 */
.dialog-footer {
  text-align: right;
}
</style>